import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import { saveAs } from 'file-saver' // 推荐使用 file-saver 处理文件保存

const service = axios.create({
    baseURL: 'http://203.189.6.175:9999',
    timeout: 15000
})

// 定义无需认证的接口白名单
const AUTH_WHITELIST = [
    '/api/auth/login'
]

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 处理 Blob 请求
        if (config.responseType === 'blob') {
            config.headers['Content-Type'] = 'application/json' // 保持 JSON 请求头
        }

        // 检查白名单逻辑
        const isAuthRequest = AUTH_WHITELIST.some(path => config.url.includes(path));

        if (!isAuthRequest) {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
        }
        return config;
    },
    error => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
    async response => {
        // Blob 响应处理（导出 Excel）
        if (response.config.responseType === 'blob') {
            return handleBlobResponse(response)
        }

        // 正常 JSON 响应处理
        if (response.data?.code === 400) {
            handleTokenExpired()
            return Promise.reject(response.data)
        }
        return response.data
    },
    async error => {
        // Blob 响应错误处理
        if (error.config?.responseType === 'blob') {
            try {
                const text = await blobToText(error.response.data)
                const result = JSON.parse(text)
                Message.error(result.msg || '导出失败')
                return Promise.reject(result)
            } catch (e) {
                Message.error('文件解析失败')
                return Promise.reject(e)
            }
        }

        // 常规错误处理
        if (error.response) {
            const { status, data } = error.response
            if (status === 400 || data?.code === 400) {
                handleTokenExpired()
            }
        }
        return Promise.reject(error)
    }
)

// Blob 响应处理器
async function handleBlobResponse(response) {
    try {
        // 获取文件名
        const filename = getFilenameFromHeaders(response.headers)

        // 创建 Blob
        const blob = new Blob([response.data], {
            type: response.headers['content-type']
        })

        // 触发文件下载
        saveAs(blob, filename)

        return {
            code: 200,
            success: true,
            filename
        }
    } catch (e) {
        // 如果 Blob 解析失败，尝试读取错误信息
        const text = await blobToText(response.data)
        const result = JSON.parse(text)
        Message.error(result.msg || '文件下载失败')
        return Promise.reject(result)
    }
}

// 从 headers 中提取文件名
function getFilenameFromHeaders(headers) {
    const disposition = headers['content-disposition'] || ''
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
    const matches = filenameRegex.exec(disposition)
    if (matches && matches[1]) {
        return matches[1].replace(/['"]/g, '')
    }
    return `export_${new Date().getTime()}.xlsx`
}

// Blob 转文本
function blobToText(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsText(blob)
    })
}

// Token失效处理函数
function handleTokenExpired() {
    localStorage.removeItem('user')
    localStorage.removeItem('token')

    Message({
        message: '登录状态已过期，请重新登录',
        type: 'warning',
        duration: 3000
    })

    router.replace({
        path: '/login',
        query: {
            redirect: encodeURIComponent(router.currentRoute.fullPath)
        }
    })
}

export default service